package com.sharp;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

public class RenameUtils {
	public static final String COPY_DIR = File.separator+"renameNewFile";
	public static void main(String[] args) throws IOException {
		if(args == null || args.length == 0){
			throw new RuntimeException("输入参数的格式不对，请输入例如：{index}-{name}{type} mp3");
		}
		String nameExpression = args[0];
		
		String[] extensions = null;
		if(args.length == 2){
			extensions = StringUtils.split(args[1], ",");
		}
		String dir = System.getProperty("user.dir");
		
		Collection<File> files = FileUtils.listFiles(new File(dir).getParentFile(), extensions, false);
		long startIndex = 0;
		for(File file : files)
		{
			Map<String, String> info = getFileInfo(file,startIndex+1);
			String newName = getFileNewName(nameExpression,info);
			FileUtils.copyFile(file, new File(file.getParent()+COPY_DIR,newName));
			System.out.println("旧文件名->"+ file.getName() + "新文件名->"+ newName);
			startIndex++;
		}
	}

	public static String getFileNewName(String nameExpression, Map<String, String> info) {
		Set<Entry<String, String>> entries = info.entrySet();
		for (Entry<String, String> entry : entries) {
			nameExpression = StringUtils.replace(nameExpression, entry.getKey(), entry.getValue());
		}
		if(nameExpression.indexOf(".")== -1){
			nameExpression += info.get(FILE_INFO.FILE_TYPE.getInfo());
		}
		return nameExpression;
	}

	public static Map<String, String> getFileInfo(File file, long index) {
		Map<String, String> fileInfos = new HashMap<String, String>();
		fileInfos.put(FILE_INFO.FILE_INDEX.getInfo(), StringUtils.leftPad(index+"", 3, "0"));
		fileInfos.put(FILE_INFO.FILE_NAME.getInfo(), StringUtils.substring(file.getName(), 0,StringUtils.lastIndexOf(file.getName(), ".")));
		fileInfos.put(FILE_INFO.FILE_SIZE.getInfo(), FileUtils.sizeOf(file) + "");
		fileInfos.put(FILE_INFO.FILE_TYPE.getInfo(), StringUtils.substring(file.getName(), StringUtils.lastIndexOf(file.getName(), ".")));
		return fileInfos;
	}
}
